#include "ipchangethread.h"


IpChangeThread::IpChangeThread(QString h, QString i, QString m, QObject *parent) :
    QThread(parent),
    m_hostIPString(h),
    m_ipString(i),
    m_maskString(m)
{
}

void IpChangeThread::run(){
    QTcpSocket* socket = new QTcpSocket();
    QStringList ipBytesString = m_ipString.split('.');
    QStringList maskBytesString = m_maskString.split('.');
    char ipBytes[4];
    char maskBytes[4];
    if(ipBytesString.size() != 4){
        emit sig_msg("error");
        delete socket;
        socket = 0;
        return; //Error
    }
    if(maskBytesString.size() != 4){
        emit sig_msg("error");
        delete socket;
        socket = 0;
        return; //Error
    }
    for(int i = 0; i<4;++i){
        ipBytes[i] = (char)ipBytesString[i].toInt();
        maskBytes[i] = (char)maskBytesString[i].toInt();
    }
    QString dataToSend = "GET /?IP";
    dataToSend += ipBytes[0];
    dataToSend += ipBytes[1];
    dataToSend += ipBytes[2];
    dataToSend += ipBytes[3];
    dataToSend += maskBytes[0];
    dataToSend += maskBytes[1];
    dataToSend += maskBytes[2];
    dataToSend += maskBytes[3];
    socket->connectToHost(QHostAddress(m_hostIPString),11110);
    if(!socket->waitForConnected(SOCKET_TIMEOUT)){
        emit sig_msg("error");
        delete socket;
        socket = 0;
        return; //Error
    }
    socket->write(dataToSend.toAscii());
    if(!socket->waitForBytesWritten(SOCKET_TIMEOUT)){
        emit sig_msg("error");
        delete socket;
        socket = 0;
        return; //Error
    }
    if(!socket->waitForReadyRead(SOCKET_TIMEOUT)){
        emit sig_msg("error");
        delete socket;
        socket = 0;
        return; //Error
    }
    int by = socket->bytesAvailable();
    char* data = new char[by];
    if(socket->read(data,by) != -1){
        QString message(data);
        if(!message.contains("Updated")){
            emit sig_msg("error");
            delete socket;
            socket = 0;
            return; //Error
        }
    }
    socket->close();
    emit sig_msg("success");
    delete socket;
    socket = 0;
    return; //Success

}
